import { Province, getChinaProvince, getCity, getCounty} from "../../utils/data/data";
import Toast from '@vant/weapp/toast/toast';
import { H2oMoment } from "../../utils/bo";
import { formatTime } from "../../utils/functions";
import { DoCreateMoment } from "../../utils/httpcall";

// pages/moment/moment.ts
Page({
  data: {
    maxSize:1024*300,
    title:'',
    content:'',
    locations:'',
    show: false,
    fileList:[],
    pandding:false,
    options:Array<Province>()
  },
  onShow(){
    const proviceList = getChinaProvince()
    this.setData({options:proviceList})
  },
  afterRead(e:any) {
    const file = e.detail.file 
    const fileList = this.data.fileList
    this.setData({ fileList: fileList.concat(file) });
  },
  delete(e:any) {
    const {index} = e.detail;
    const fileList = this.data.fileList
    fileList.splice(index, 1);
    this.setData({ fileList: fileList });
  },
  onSend(_e:any){
    const title = this.data.title
    const content = this.data.content
    const locations = this.data.locations
    const fl = this.data.fileList.length
    if((title === "")||(content === "")||(locations === "")||(fl === 0)){
      Toast("请补充完必要内容")
      return 
    }
    if(this.data.pandding){
      return 
    }
    const moment = new H2oMoment()
    moment.title = title
    moment.location = locations
    moment.content = content
    const {url} = this.data.fileList[0]
    moment.img = url
    moment.ctime = formatTime(new Date())
    this.setData({pandding: true})
    DoCreateMoment(moment, (_res:any)=>{
      Toast("发表成功")
      this.setData({pandding: false, title:"",locations:"", content:""})
    }, (_res:any)=>{
      Toast("发表失败")
      this.setData({pandding: false})
    })
  },
  onClose(_e:any){
    this.setData({show:false})
  },
  onFinish(e:any){
    const {selectedOptions} = e.detail
    const locations = `${selectedOptions[0].text}|${selectedOptions[1].text}|${selectedOptions[2].text}` 
    this.setData({locations:locations, show:false})
  },
  onLClick(_e:any){
    this.setData({show:true})
  },
  onChange(e:any){
    const { tabIndex, value } = e.detail;
    if(tabIndex === 0){
      const cityList = getCity(value)
      let options = this.data.options
      for(var i = 0; i < options.length;i++){
        if(value === options[i].value){
          options[i].children = cityList
          this.setData({options:options})
          break
        }
      }
    }else if(tabIndex === 1){
      const countrys = getCounty(value)
      const options = this.data.options
      const prefix = value.slice(0, 2)
      for(var i = 0; i < options.length;i++){
        if(!options[i].value.startsWith(prefix)){
          continue
        }
        for(var j = 0; j < options[i].children.length;j++){
          if(value === options[i].children[j].value){
            options[i].children[j].children = countrys
            this.setData({options:options})
            break
          }
        }
        break
      }
    }
  }
})